package com.amsp.oa.oademo.controller;

import com.amsp.oa.oademo.entity.FixedAssetInventory;
import com.amsp.oa.oademo.service.FixedAssetInventoryService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/fixed-asset-inventory")
@Api(tags = "固定资产盘点管理")
@CrossOrigin
public class FixedAssetInventoryController {

    @Autowired
    private FixedAssetInventoryService fixedAssetInventoryService;

    @PostMapping("/save")
    @ApiOperation("保存固定资产盘点记录")
    public boolean save(@RequestBody Map<String, Object> params) {
        List<Map<String, Object>> inventoryMapList = (List<Map<String, Object>>) params.get("inventoryList");
        String reviewer = (String) params.get("reviewer");
        String confirmer = (String) params.get("confirmer");
        String sampler = (String) params.get("sampler");
        String rechecker = (String) params.get("rechecker");
        String initialChecker = (String) params.get("initialChecker");

        // 将Map转换为FixedAssetInventory对象
        List<FixedAssetInventory> inventoryList = convertToEntityList(inventoryMapList);

        // 如果有ID，则调用更新方法，否则调用保存方法
        return fixedAssetInventoryService.saveBatch(inventoryList, reviewer, confirmer,
                sampler, rechecker, initialChecker);
    }

    @GetMapping("/list")
    @ApiOperation("获取固定资产盘点列表")
    public IPage<FixedAssetInventory> list(
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("资产编号") @RequestParam(required = false) String assetCode,
            @ApiParam("资产名称") @RequestParam(required = false) String assetName,
            @ApiParam("所属部门") @RequestParam(required = false) String department,
            @ApiParam("管理责任人") @RequestParam(required = false) String responsiblePerson,
            @ApiParam("开始日期") @RequestParam(required = false) String startDate,
            @ApiParam("结束日期") @RequestParam(required = false) String endDate) {
        return fixedAssetInventoryService.getPage(current, size, assetCode, assetName,
                department, responsiblePerson, startDate, endDate);
    }

    @GetMapping("/{id}")
    @ApiOperation("获取固定资产盘点详情")
    public FixedAssetInventory getById(@PathVariable Long id) {
        return fixedAssetInventoryService.getById(id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除固定资产盘点记录")
    public boolean delete(@PathVariable Long id) {
        return fixedAssetInventoryService.removeById(id);
    }

    // 抽取公共的转换方法
    private List<FixedAssetInventory> convertToEntityList(List<Map<String, Object>> mapList) {
        return mapList.stream()
                .map(map -> {
                    FixedAssetInventory inventory = new FixedAssetInventory();

                    // 设置ID（如果存在）
                    if (map.containsKey("id")) {
                        inventory.setId(Long.valueOf(map.get("id").toString()));
                    }

                    // 设置基本字段
                    inventory.setAssetCode((String) map.get("assetCode"));
                    inventory.setAssetName((String) map.get("assetName"));
                    inventory.setSpecification((String) map.get("specification"));
                    inventory.setUnit((String) map.get("unit"));
                    inventory.setDepartment((String) map.get("department"));
                    inventory.setStorageLocation((String) map.get("storageLocation"));
                    inventory.setResponsiblePerson((String) map.get("responsiblePerson"));
                    inventory.setRemarks((String) map.get("remarks"));

                    // 处理数字类型
                    if (map.get("initialCount") != null) {
                        inventory.setInitialCount(((Number) map.get("initialCount")).intValue());
                    }
                    if (map.get("recheckCount") != null) {
                        inventory.setRecheckCount(((Number) map.get("recheckCount")).intValue());
                    }
                    if (map.get("sampleCount") != null) {
                        inventory.setSampleCount(((Number) map.get("sampleCount")).intValue());
                    }

                    // 处理金额字段
                    if (map.get("originalPrice") != null && !map.get("originalPrice").toString().isEmpty()) {
                        inventory.setOriginalPrice(new BigDecimal(map.get("originalPrice").toString()));
                    }
                    if (map.get("accumulatedDepreciation") != null
                            && !map.get("accumulatedDepreciation").toString().isEmpty()) {
                        inventory.setAccumulatedDepreciation(
                                new BigDecimal(map.get("accumulatedDepreciation").toString()));
                    }
                    if (map.get("netValue") != null && !map.get("netValue").toString().isEmpty()) {
                        inventory.setNetValue(new BigDecimal(map.get("netValue").toString()));
                    }

                    // 处理日期
                    if (map.get("purchaseDate") != null && !map.get("purchaseDate").toString().isEmpty()) {
                        inventory.setPurchaseDate(LocalDate.parse((String) map.get("purchaseDate")));
                    }

                    return inventory;
                })
                .collect(Collectors.toList());
    }
}